package com.wy.demo.ftp;

import java.io.*;
import java.net.Socket;

public class FtpFileTransfer {

    public void uploadFileWithTempSuffix(String server, int port, String username, String password, String localFilePath, String remoteDirectory) throws IOException {

        Socket socket = null;
        BufferedReader controlReader = null;
        PrintWriter controlWriter = null;

        try {
            // 连接到FTP服务器
            socket = new Socket(server, port);
            controlReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            controlWriter = new PrintWriter(socket.getOutputStream(), true);

            // 读取欢迎消息
            String response = controlReader.readLine();
            System.out.println("服务器响应: " + response);

            // 用户认证
            controlWriter.println("USER " + username);
            response = controlReader.readLine();
            System.out.println(response);

            controlWriter.println("PASS " + password);
            response = controlReader.readLine();
            System.out.println(response);

            // 设置二进制传输模式
            controlWriter.println("TYPE I");
            response = controlReader.readLine();
            System.out.println(response);

            // 进入被动模式
            controlWriter.println("PASV");
            response = controlReader.readLine();
            System.out.println(response);

            // 解析被动模式响应获取数据端口
            int dataPort = parsePassiveResponse(response);

            // 准备文件名
            File localFile = new File(localFilePath);
            String fileName = localFile.getName();
            String tempFileName = fileName + ".now";
            String remoteTempPath = remoteDirectory + tempFileName;
            String remoteFinalPath = remoteDirectory + fileName;

            // 建立数据连接
            Socket dataSocket = new Socket(server, dataPort);

            // 发送STOR命令（临时文件名）
            controlWriter.println("STOR " + remoteTempPath);
            response = controlReader.readLine();
            System.out.println(response);

            // 传输文件
            transferFile(localFile, dataSocket);

            // 关闭数据连接
            dataSocket.close();

            // 读取传输完成响应
            response = controlReader.readLine();
            System.out.println("传输完成: " + response);

            // 重命名文件（去掉.now后缀）
            controlWriter.println("RNFR " + remoteTempPath);
            response = controlReader.readLine();
            System.out.println(response);

            controlWriter.println("RNTO " + remoteFinalPath);
            response = controlReader.readLine();
            System.out.println("重命名完成: " + response);

            System.out.println("文件传输成功: " + fileName);

        } finally {
            // 清理资源
            if (controlWriter != null) {
                controlWriter.println("QUIT");
                controlWriter.close();
            }
            if (controlReader != null) controlReader.close();
            if (socket != null) socket.close();
        }
    }

    private int parsePassiveResponse(String response) {
        // 解析PASV响应: 227 Entering Passive Mode (192,168,1,1,20,21)
        int start = response.indexOf('(');
        int end = response.indexOf(')');
        String[] parts = response.substring(start + 1, end).split(",");

        int port1 = Integer.parseInt(parts[4]);
        int port2 = Integer.parseInt(parts[5]);
        return port1 * 256 + port2;
    }

    private void transferFile(File localFile, Socket dataSocket) throws IOException {
        try (FileInputStream fis = new FileInputStream(localFile);
             OutputStream dataOut = dataSocket.getOutputStream()) {

            byte[] buffer = new byte[8192];
            int bytesRead;
            long totalBytes = 0;
            long fileSize = localFile.length();

            System.out.println("开始传输文件: " + localFile.getName() + " (大小: " + fileSize + " 字节)");

            while ((bytesRead = fis.read(buffer)) != -1) {
                dataOut.write(buffer, 0, bytesRead);
                totalBytes += bytesRead;

                // 显示进度
                int progress = (int) ((totalBytes * 100) / fileSize);
                System.out.printf("\r传输进度: %d%% (%d/%d 字节)", progress, totalBytes, fileSize);
                Thread.sleep(2000);
            }
            System.out.println("\n文件数据传输完成");
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
}